package com.me.videoservice.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.me.videoservice.model.entry.DeviceInfo;
import com.me.videoservice.model.query.DeviceInfoQuery;
import com.me.videoservice.service.DeviceInfoService;
import java.time.LocalDateTime;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1/device/")
@CrossOrigin
public class DeviceInfoController {

  @Resource
  private DeviceInfoService deviceInfoService;

  @GetMapping("query_all")
  public R<List<DeviceInfo>> queryAll() {
    return R.ok(deviceInfoService.queryAllDeviceInfoWithLocation());
  }

  @PostMapping("query")
  public R<Page<DeviceInfo>> query(@RequestBody DeviceInfoQuery param) {
    return R.ok(deviceInfoService
        .page(
            new Page<>(
                param.getPageable().getPage(),
                param.getPageable().getPageCount()),
            Wrappers.<DeviceInfo>query()
                .eq(param.getOnlineState() != null, "offline_flag", param.getOnlineState())
                .eq(param.getPushState() != null, "push_flag", param.getPushState())
                .between(
                    param.getDeviceAddDateStart() != null && param.getDeviceAddDateEnd() != null,
                    "created_at",
                    param.getDeviceAddDateStart() == null ? null
                        : param.getDeviceAddDateStart().atTime(0, 0, 0, 0),
                    param.getDeviceAddDateEnd() == null ? null
                        : param.getDeviceAddDateEnd().atTime(23, 59, 59, 999))
        )
    );
  }

  @PostMapping("save")
  public R<Boolean> save(@RequestBody DeviceInfo deviceInfo) {
    LocalDateTime now = LocalDateTime.now();
    if (deviceInfo.getId() == null) {
      deviceInfo.setCreatedAt(now);
    }
    deviceInfo.setUpdatedAt(now);
    return R.ok(deviceInfoService.saveDevice(deviceInfo));
  }

  @DeleteMapping("delete/{id}")
  public R<Boolean> delete(@PathVariable("id") Long id) {
    return R.ok(deviceInfoService.removeById(id));
  }
}
